/**
 * @author {Yuntao Zhou}
 */
var QS_Commodity=function(){
    this.containerId = null;
    this.container = null;
    this.id = null;
    this.profile = null;
    this.el = null;
    this.groupTickers={};
    this.tickers={};//commodity tickers list
    this.dataScrollPN =null;
    this.tabMenuData=null;
    this.currentTab=null;
    this.pause = false;
    this.tabMenu=null;
    this.lastActiveTabId=0;
    this.DOMMap={};//dom map
    this.width=null;//component width
    this.height=null;//component height
    this.dataPointList=null;//data point list
    this.ColModel=[];
    this.gridColumnWidth=60;//grid column width
    this.groupGridList=[];//store the groupGrid
    this.hideGroupGridList=[];
    this.filterMonths=6;
    
    this.Html='<div class="rtq-commodity"><div class="hd"><div class="tabmenu"></div></div><div class="bd"><div class="data"></div></div></div>'
};
QS_Commodity.prototype={
    init:function(ContainerId,Profile,Sid,width,height){
        this.containerId = ContainerId;
        this.container = $('#'+ContainerId);
        this.id = Sid;
        this.profile = Profile;
        this.el=$(this.Html);
        this.el.appendTo(this.container);
        //add
        this.defaultDataPointList={
            "ExpDate":{
                title:'Exp. Date',
                width:this.gridColumnWidth,
                align:'left',
                dataType:'string'
            },
            "LastPrice":{
                title:'Last',
                width:this.gridColumnWidth,
                align:'right',
                dataType:'float'
            },
            "Chg":{
                title:'Chg',
                width:this.gridColumnWidth,
                align:'right',
                dataType:'float'
            },
            "OpenPrice":{
                title:'Open',
                width:this.gridColumnWidth,
                align:'right',
                dataType:'float'
            },
            "HighPrice":{
                title:'High',
                width:this.gridColumnWidth,
                align:'right',
                dataType:'float'
            },
            "LowPrice":{
                title:'Low',
                width:this.gridColumnWidth,
                align:'right',
                dataType:'float'
            }
        };
        this.dataPointList={
            "ExpDate":{
                width:60
            },
            "LastPrice":{
                width:60
            },
            "Chg":{
                width:60
            },
            "OpenPrice":{
                width:60
            },
            "HighPrice":{
                width:60
            },
            "LowPrice":{
                width:60
            }
        };
        this.width=width;
        this.height=height;
        if(Profile){
            this.width=Profile.width||width;
            this.height=Profile.height-54||height;
            this.dataPointList=Profile.dataPointList||this.defaultDataPointList;
            this.groupTickers=Profile.groupTickers;
            this.tickers=this._convertToTickers(this.groupTickers)||{};
            this.lastActiveTabId=Profile.lastActiveTabId||0;
            this.filterMonths=Profile.filterMonths||6;
        }
        this.tabMenuData=[{id:0,txt:"Energy",closable: false},{id:1,txt:"Agriculture",closable: false},{id:2,txt:"Metals",closable: false},{id:3,txt:"Index",closable: false}]
        this.dataScrollPN = new Util.ScrollPanel($('div.data',this.el), {}, {
            onScroll: function(sl, st){
            }
        });
        this.createGridGroup();
        this.createMenu();
        if (this.getTitle() == 'Commodity') {
            this.setTitle('Futures');
        }
    },
    getGridWidth:function(dataPointList){
        var gridWidth=0,hide;
        for(var p in dataPointList){
            hide=dataPointList[p]["hide"]||this.defaultDataPointList[p]["hide"];
            if (!hide) {
                gridWidth += dataPointList[p].width;
            }
        }
        return gridWidth;
    },
    changeOutSize:function(w,h){
        var parent = this.el.parent().parent();
        w = w || parent.width();
        h = h || parent.height();
        var flag=false;
        if(this.width!=w){
            this.width=w;
            flag=true;
        }
        if(this.height!=h-28){
            this.height=h-28;
            flag=true;
        }
        if(flag){
            this.createGridGroup();
            this.reBindGroupGrid(this.tickers[this.currentTab.txt],false);
        }        
    },
    createMenu:function(){
        var self=this;
        this.tabMenu=new Util.TabMenu($('.tabmenu',this.el)[0], this.tabMenuData, {
            onActive: function(tab){
                self.currentTab=tab;
                self.createTab(self.currentTab);
            },
            onDeActive:function(tab){
                self.unSubsciberTickers(self._convertToSymbols(self.tickers[tab.txt]));
            }
        },{
            width: 120,
            tabsList:true,
            activeTabId:self.lastActiveTabId
        });
    },
    createTab:function(tab){
        var self=this;
        
        self.showLoading(true);
        
        if(self.tickers[tab.txt]){
            self.reBindGroupGrid(self.tickers[tab.txt]);    
        }else{
            DBHelper.getCommodity(tab.txt,function(o){
                if (o == null || o == '' ||!o) {
                    return false;
                }
                o= $.evalJSON(o);
                self.tickers[tab.txt]=self._filterData(o[tab.txt]);
                self.reBindGroupGrid(self.tickers[tab.txt]);                
            });         
        }
        self.hideLoading();
    },
    _filterData:function(o){
        var details,today=new Date(),year=(today.getFullYear()+'').substring(0,2);
        for(var g in o){
            details=o[g]["Details"];
            var len=details.length,date,ticker,tempArray=[];
            for(var i=0;i<len;i++){
                if(tempArray.length==this.filterMonths){
                    break;
                }
                ticker=details[i][0];
                date=details[i][1].split("/");
                date=year+date[2]+"-"+date[0]+"-"+date[1];
                date=new Date(date.replace(/\-/g, "\/")); 
                if(date>today&&ticker.charAt(ticker.length-1).toLowerCase()!='y'){
                    tempArray.push(details[i]);
                }
            }
            o[g]["Details"]=tempArray;
        }
        return o;
    },
    _convertToSymbols:function(data){//data={"A":{"Exch":"","Details":[["",""],["",""]]},"B":{"Exch":"","Details":[[],[]]}}
        var symbols=[],details,len,exchId;
        for(var o in data){
            details=data[o]["Details"];
            exchId=data[o]["FeedSrcId"];
            len=details.length;
            for(var i=0;i<len;i++){
                symbols.push(exchId+":"+details[i][0]);
            }
        }
        return symbols;
    },
    _convertToTickers:function(groupTickers){
        for(var o in groupTickers){
            this.tickers[o]=groupTickers[o];
        }
    },
    _convertToGridData:function(tickers){//obj={"":[["",""],["",""],["",""]],"":[["",""],["",""],["",""]]}
        var arr=[],exchId,symbol,name;
        for(var o in tickers){
            exchId=this.tickers[this.currentTab.txt][o]["FeedSrcId"];   
            name=this.tickers[this.currentTab.txt][o]["Name"]||'';  
            var idx=name.indexOf('Cont.');
            if(idx>-1){
                name=name.substring(0,idx);
            }     
            for(var i=0;i<tickers[o].length;i++){
                var tObj={},j=0;
                symbol=exchId+":"+tickers[o][i][0];
                tObj["Group"]=name;
                tObj["Symbol"]=symbol;              
                for(var p in this.dataPointList){
                    if(j==0){
                        tObj[p] = tickers[o][i][1];
                    }else{
                        if(!gData[symbol]){
                            gData[symbol]={};
                        }
                        tObj[p]=gData[symbol][p]?gData[symbol][p].toFixed(2):'';
                    }
                    j++;
                }
                arr.push(tObj);
            }       
        }
        return arr;
    },
    _mappingGroupNamebyTicker:function(ticker){
        var maps={"@CL":"Sweet Crude Oil Globex","@BZ":"Brent Crude Oil Last Day","@NG":"Natural Gas Globex","@HO":"Heating Oil Globex","@RBO":"RBOB Gasoline",
                "S":"Soybeans","SM":"Soybean Meal","BO":"Soybean Oil","O":"Oats","CJ":"Cocoa (NYMEX)","W":"Wheat","C":"Corn","RR":"Rough Rice CBOT","KT":"Coffee C (NYMEX)",
                "TT":"Cotton #2 (NYMEX)","YO":"Sugar No. 11 (NYMEX)","@GC":"Comex Gold Globex","@HG":"Comex Copper Globex","@SI":"Comex Silver Globex","@PL":"Platinum Globex",
                "DRE":"DJ US Real Estate Index","@MD":"S&P MidCap 400 Index GLOBEX","@ND":"Nasdaq 100 Index GLOBEX","@SG":"S&P 500 Citigroup Growth Index","@SP":"S&P 500 Index GLOBEX",
                "@SU":"S&P 500 Citigroup Value Index","DJ":"Dow Jones Industrial Avg","DD":"BIG Dow DJIA ($25) Futures","@SMP":"S&P SmallCap 600","DJC":"DJ-UBS Commodity Index Future",
                "GI":"S&P GSCI Commodity Index","GIS":"S&P GSCI Commodity Index Side-by-Side","YM":"Mini DJ Indust $5 e-cbot","ZD":"DJ Industrial e-cbot"};
        return maps[ticker];
    },
    _splitData:function(data,num){//data={"A":{"Exch":"","Details":[["",""],["",""]]},"B":{"Exch":"","Details":[[],[]]}}
        var index,tickers=[];
        for (var i = 0; i < num; i++) {
            tickers[i]={};
            groupTickers={};
            index=0;
            for(var o in data){
                if(index%num==i){
                    tickers[i][o]=data[o]["Details"];
                }
                index++;
            }
        }       
        return tickers;
    },
    _getMax:function(list){
        var max=list[0],len=list.length;
        for(var i=0;i<len;i++){
            if(max<=list[i]){
                max=list[i];
            }
        }
        return max;
    },
    reBindGroupGrid:function(data,needSubcribe){
        needSubcribe=needSubcribe===false?false:true;
        if(!data||data==null){
            data={};
        }
        var groupGrid,tickers,
            len=this.groupGridList.length,heightList=[];
        for(var i=0;i<len;i++){
            tickers=this._splitData(data,len);
            groupGrid=this.groupGridList[i];
            groupGrid.reBindData(this._convertToGridData(tickers[i]));
            heightList.push(groupGrid.body[0].scrollHeight+22);
        } 
        var maxHeight=this._getMax(heightList)+30;
        var gridWidth=this.getGridWidth(this.dataPointList)+13;
        for(var i=0;i<len;i++){
            this.groupGridList[i].resize(gridWidth,maxHeight);
            for(var o in this.groupGridList[i].DOMMap){
                this.DOMMap[o]=this.groupGridList[i].DOMMap[o];
            }
        }   
        this.el.find('data').css({ width: this.width + "px", height: this.height + "px" });
        this.dataScrollPN.reSize(this.width,this.height);
        if(needSubcribe){
            this.subsciberTickers(this._convertToSymbols(data));
        }
        this.forceUpdateData();
    },
    //force update data in DOM, without flash
    _forceUpdatebyRow: function(gKey){
        var aData = {};
        for(var field in this.defaultDataPointList){
            aData[field] = {
                dataType: this.defaultDataPointList[field].dataType,
                value: gData[gKey] == null ? null : gData[gKey][field]||null
            };
        }
        this.updateData(gKey, aData);
    },
    forceUpdateData:function(){
        var gKeyList=this._convertToSymbols(this.tickers[this.currentTab.txt]);
        for(var i=0,l=gKeyList.length;i<l;i++){
            this._forceUpdatebyRow(gKeyList[i]);
        }
    },
    createGridGroup:function(){
        var self=this,
            cols=[],
            gridEl,
            gridWidth=this.getGridWidth(this.dataPointList)+13;
            num=parseInt((this.width-12)/(gridWidth+5)),
            groupGridSize=this.groupGridList.length;
            
        num=(num==0)?1:num;
        if(num==groupGridSize){
            return;
        }else if(num>groupGridSize){
            this.DOMMap={};
            this.ColModel=this.createColModel();    
            var hLen=this.hideGroupGridList.length; 
            for(var i=groupGridSize;i<num;i++){
                hLen=this.hideGroupGridList.length;
                if (hLen != 0) {
                    this.groupGridList.push(this.hideGroupGridList.pop());
                    this.el.find('.data .rtq-com-grid').eq(i).show();
                }
                else{
                    gridEl = $('<div class="rtq-com-grid"></div>').css({
                        'width': gridWidth,
                        'float': 'left',
                        'margin-left': '5px',
                        'margin-top': '5px'
                    }).appendTo(this.el.find('.data'));
                    this.groupGridList.push(this.createGrid(gridEl, gridWidth, this.height, this.ColModel));
                }
            }   
        }else{
            this.DOMMap = {};   
            for(var i=num;i<groupGridSize;i++){
                this._clearGrid(i); 
            }
            this.groupGridList.splice(num,groupGridSize-num);   
        }
    },
    _clearGrid:function(index){     
        if (index) {
            this.groupGridList[index].empty();
            this.hideGroupGridList.push(this.groupGridList[index]);         
            this.el.find('.data .rtq-com-grid').eq(index).hide();
        }
        else {
            this.unSubsciberTickers(this._convertToSymbols(this.tickers[this.currentTab.txt]));
            for(var i=0;i<this.groupGridList.length;i++){
                this.groupGridList[i].empty();
            }
            this.groupGridList = [];
            this.hideGroupGridList=[];
            this.DOMMap = {};
            this.el.find('.data .rtq-com-grid').remove();
        }
        
    },
    createColModel:function(){
        var cols=[],col,defCol;
        for(var p in this.dataPointList){
            col=this.dataPointList[p];
            defCol=this.defaultDataPointList[p];    
            cols.push({
                header: col["title"]||defCol["title"]||'',
                dataIndex: p,
                dataType: col["dataType"]||defCol["dataType"],
                width: col["width"]||defCol["width"],
                align: col["align"]||defCol["align"],
                hide:col["hide"]||defCol["hide"]||false
            });                     
        }
        return cols;    
    },
    createGrid:function(container, w, h, cols){
        var grid=new Util.DataGrid(container,{},{
            column:cols,
            width:w,
            height:h,
            indexColKey:'Symbol',
            fixSize:false,
            groupDataIndex: 'Group',
            sortable: false,
            cellResize: false,
            cellRearrange: false
        },{});
        return grid;
    },
    addTikers:function(tickers){
        this.addDOM(tickers);
    },
    _addDOM:function(tickers){
        
    },
    updateData:function(gKey,oData){
        if(!this.DOMMap[gKey]){
            return;
        }
        var type, gValue, oValue;
        for(var field in oData){
            if (!oData.hasOwnProperty(field)) {
                continue;
            }
            type = oData[field].dataType;
            gValue = gData[gKey] == null ? null : gData[gKey][field];
            oValue = oData[field].oValue;
            if (gValue){
                this._updateDOM(gKey, field, gValue, oValue, type);
            }
        }
    },
    _updateDOM:function(gKey, field, data, oldData, type){
        var el = this.DOMMap[gKey][field];
        if(!el || el == null){return;}
        switch (field) {
            case 'LastPrice':{
                type = 'f';
                flash(el, data, oldData);
            }break;
            case 'Chg':{
                type = 'f';
                flashWithDirectional(el, data, oldData,data >= 0);
                //el.style.color = data >= 0 ?  QS_Style.greenFontColor : QS_Style.redFontColor;
            }break;
            case 'OpenPrice':{
                type = 'f';
                flash(el, data, oldData);
            }break;
            case 'HighPrice':{
                type = 'f';
                flash(el, data, oldData);
            }break;
            case 'LowPrice':{
                type = 'f';
                flash(el, data, oldData);
            }break;
             default:{
                
            }break;
        }
        if(type='f'){
            data=(data==null?'':data.toFixed(2));
        }
        el.innerHTML=data;
    },
    subsciberTickers:function(tickers){
        var list = [];var ls ,gKey;
        if(tickers==null||tickers.length==0){
            return;
        }
        var len=tickers.length;
        for(var i=0;i<len;i++){
            gKey=tickers[i];
            ls = gKey.split(":");
            list.push({gkey:gKey,paraList:[{sourceType:"D",serviceName:ls[0],itemName:"3"+push.subSeparator+ls[1]+push.subSeparator+"-1"}],isSubscribeLevelII:false,futureType:'3'});//futureType for pull forex data
            if(!gData[gKey]){
                gData[gKey] = {tenforeTicker:ls[1],tenforeCode:ls[0],ticker:ls[1]};
            }
        }
        if(list.length>0){
            if (push && push.proxy) {
                push.proxy.batchSubscribe(list);
            }
        }
    },
    unSubsciberTickers:function(tickers){
        var list = [];var ls ,gKey;
        if(tickers==null||tickers.length==0){
            return;
        }
        var len=tickers.length;
        for(var i=0;i<len;i++){
            gKey=tickers[i];
            ls = gKey.split(":");
            list.push({gkey:gKey,paraList:[{sourceType:"D",serviceName:ls[0],itemName:"3"+push.subSeparator+ls[1]+push.subSeparator+"-1"}],isSubscribeLevelII:false,futureType:'3'});
            if(!gData[gKey]){
                gData[gKey] = {tenforeTicker:ls[1],tenforeCode:ls[0],ticker:ls[1]};
            }
        }
        if(list.length>0){
            if (push && push.proxy) {
                push.proxy.batchUnsubscribe(list);
            }
        }
    },
    groupTickers:function(tickers){
        for(var ticker in tickers){
            var symbol=ticker.substring(3,5);
            if(this.groupTickers[symbol]){
                this.groupTickers[symbol].push(ticker)
            }else{
                this.groupTickers[symbol]=[];
            }
        }   
    },
    mappingDate:function(ticker){
        var monthCodes={
            "F":"JAN",
            "G":"FEB",
            "H":"MAR",
            "K":"MAY",
            "M":"JUN",
            "N":"JUL",
            "Q":"AUG",
            "U":"SEP",
            "V":"OCT",
            "X":"NOV",
            "Z":"DEC",
            "Y":"RES"
        };
        var len=ticker.length;      
        var yCode=ticker.substring(len-2,len-1);
        var mCode=ticker.substring(len-1,len);
        return{
            "year":yCode,
            "month":monthCodes[mCode]
        };
    },
    saveConfig:function(){
        return {
            //groupTickers:this.groupTickers,
            lastActiveTabId:this.currentTab.id,
            title:this.getTitle()
        }
    },
    clear:function(){
        this._clearGrid();
        this.el.unbind(".commodity");
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }
};